package com.landun.market.web.interceptor;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.landun.market.pojo.Constants;
import com.landun.market.pojo.enums.ResponseCode;
import com.landun.market.web.domain.ApiOut;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.util.Optional;

/**
 * @author jiang.chuan
 * @date 2018-05-12
 */
public class InterceptorUtils {
    private static Gson gson = new GsonBuilder().setDateFormat(Constants.DATE_TIME_FORMAT).create();

    public static boolean isAjaxRequest(HttpServletRequest request, Class handlerClass, Method handlerMethod) {
        return (null != handlerClass.getAnnotation(RestController.class)
                || null != handlerMethod.getAnnotation(ResponseBody.class)
                || "XMLHttpRequest".equalsIgnoreCase(request.getHeader("X-Requested-With")));
    }


    /**
     * Ajax 返回错误信息
     *
     * @param response     HttpServletResponse
     * @param responseCode ResponseCode
     * @throws IOException IOException
     */
    public static void ajaxReturn(HttpServletResponse response, ResponseCode responseCode) throws IOException {
        ajaxReturn(response, responseCode, null);
    }

    /**
     * Ajax 返回错误信息
     *
     * @param response     HttpServletResponse
     * @param responseCode ResponseCode
     * @param message      提示错误消息
     * @throws IOException IOException
     */
    public static void ajaxReturn(HttpServletResponse response, ResponseCode responseCode, String message) throws IOException {
        responseCode = Optional.ofNullable(responseCode).orElse(ResponseCode.UNAUTHORIZED);
        message = StringUtils.isBlank(message) ? responseCode.desc() : message;

        ApiOut apiOut = new ApiOut.Builder<>().code(responseCode).message(message).build();
        response.setCharacterEncoding(Constants.DEFAULT_CHAR_SET);
        response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        PrintWriter out = response.getWriter();
        out.print(gson.toJson(apiOut));
        out.flush();
    }

}
